//
//  LocationTool.m
//  mxh_location
//
//  Created by 李财 on 2022/2/22.
//

#import "LocationTool.h"
#import <CoreLocation/CoreLocation.h>

@interface LocationTool () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locManager;
@property (nonatomic, strong) NSString * latitude;
@property (nonatomic, strong) NSString * longitude;
@end

@implementation LocationTool


// 开始定位
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled] == NO) {
        NSLog(@"locationServicesEnabled false");
    } else {
        CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
        if(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted) {
            NSLog(@"authorizationStatus failed");
        } else {
            self.locManager.delegate = self;
            //持续定位
//            [self.locManager requestAlwaysAuthorization];
            //当使用中开启定位
            [self.locManager requestWhenInUseAuthorization];
            [self.locManager startUpdatingLocation];
        }
    }
}

// 结束定位
- (void)stopLocation{
    self.locManager.delegate = nil;
    [self.locManager stopUpdatingLocation];
}


#pragma 代理回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *loc = locations.firstObject;
//    NSLog(@"----- i = %d, 维度: %f, 经度: %f", i++, loc.coordinate.latitude, loc.coordinate.longitude);
    self.latitude = [NSString stringWithFormat:@"%f", loc.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f", loc.coordinate.longitude];
    _currentLocation(self.latitude, self.longitude);
}



#pragma 懒加载
- (CLLocationManager *)locManager
{
    if (!_locManager) {
        _locManager = [[CLLocationManager alloc] init];
        if ([_locManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
            _locManager.allowsBackgroundLocationUpdates = YES;
        }
        _locManager.pausesLocationUpdatesAutomatically = NO;
        _locManager.distanceFilter = kCLDistanceFilterNone;
        _locManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    }
    return _locManager;
}


@end
